package com.neu.controller;

import com.neu.utils.ResultModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${uploadPath}")
    private String uploadPath;

    @PostMapping("/upload")
    public ResultModel upload(MultipartFile file){
        ResultModel resultModel=new ResultModel();

        //2023/11/22/???????????????????????????.jpg
        //a.jpg
        //a.jpg

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy//MM//dd");
        String relativePath = simpleDateFormat.format(new Date());

        String storePath = uploadPath +"//"+relativePath;

        if(!new File(storePath).exists()){
            new File(storePath).mkdirs();
        }

        String oriFileName = file.getOriginalFilename();
        String newFileName = UUID.randomUUID().toString().replace("-","")+oriFileName.substring(oriFileName.lastIndexOf("."));

        try{
            file.transferTo(new File(storePath+"//"+newFileName));
        } catch (IOException e) {
            //TODO 记录日志
            resultModel.setCode(500);
            resultModel.setMsg("文件上传失败");
            return resultModel;
        }

        resultModel.setData(relativePath+"//"+newFileName);
        resultModel.setMsg("文件上传成功");
        return  resultModel;
    }
}
